<template>
  <div class="bigbox">
    <el-form-item>
      <el-button type="warning" @click="addGoods">新增</el-button>
    </el-form-item>
  </div>
  <div>
    <el-table
      :data="tableData"
      stripe
      style="width: 100%"
      highlight-current-row
      :header-cell-style="{ background: '#def2fb', color: '#000' }"
      max-height="650"
    >
      <el-table-column
        align="center"
        prop="goodsname"
        label="商品名称"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        align="center"
        prop="goodsdes"
        label="商品描述"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        align="center"
        prop="price"
        label="商品单价"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        align="center"
        prop="goodsnumber"
        label="商品库存"
        :show-overflow-tooltip="true"
      />
      <el-table-column align="center" prop="imageone" label="商品封面图">
        <template #default="scope">
          <el-image
            class="tableData_image"
            :src="scope.row.imageone"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300px">
        <template #default="scope">
          <div
            style="display: flex; align-items: center; justify-content: center"
          >
            <el-button
              size="small"
              type="warning"
              @click="editGoods(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              @click="deleteGoods(scope.row.id)"
              >删除</el-button
            >
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @prev-click="getList()"
      @next-click="getList()"
      background
      v-model:page-size="pageSize"
      v-model:current-page="page"
      layout="prev, pager, next,sizes"
      :total="total"
    />

    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form
        ref="goodsForm"
        :model="form"
        :rules="rules"
        @submit.native.prevent="onSubmit"
      >
        <el-form-item
          label="商品名称"
          prop="goodsname"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.goodsname" autocomplete="on" />
        </el-form-item>
        <el-form-item
          label="商品描述"
          prop="goodsdes"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.goodsdes" autocomplete="on" />
        </el-form-item>
        <el-form-item
          label="商品单价"
          prop="price"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.price" autocomplete="on" type="number" />
        </el-form-item>
        <el-form-item
          label="商品库存"
          prop="goodsnumber"
          :label-width="formLabelWidth"
        >
          <el-input
            v-model="form.goodsnumber"
            autocomplete="on"
            type="number"
          />
        </el-form-item>
        <el-form-item label="商品展示图" prop="bannerImage">
          <el-upload
            :headers="headers"
            class="upload_image"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadImage"
            :show-file-list="false"
          >
            <el-image
              :src="form.imageone"
              v-if="form.imageone"
              class="bannerImage"
            />
            <el-icon :size="35" color="#a8abb2" v-else>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import SearchBar from "../../components/SearchBar.vue";
import {
  goodsListApi,
  imageUpload,
  goodsDeleteApi,
  goodsDetailApi,
  goodsEditApi,
  goodsAddApi,
} from "../../api/index";
import router from "@/router";
export default {
  name: "CateList",
  components: {
    SearchBar,
  },

  data() {
    return {
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      dialogFormVisible: false,
      title: "",
      form: {},
      formLabelWidth: 80,
      rules: {
        goodsname: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        goodsdes: [
          { required: true, message: "商品描述不能为空", trigger: "blur" },
        ],
        price: [
          { required: true, message: "商品单价不能为空", trigger: "blur" },
        ],
        goodsnumber: [
          { required: true, message: "商品库存不能为空", trigger: "blur" },
        ],
        imageone: [
          { required: true, message: "商品展示图不能为空", trigger: "blur" },
        ],
      },
      headers: {
        Authorization: localStorage.getItem("token"),
      },
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    //这个是监听到一页展示多少条数据的控制监听函数
    handleSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    //这个是监听点击哪一页就跳转到哪一页的监听函数
    handleCurrentChange(number) {
      this.page = number;
      this.getList();
    },
    uploadImage(param) {
      // 获取上传的文件名
      var file = param.file;
      //发送请求的参数格式为FormData
      const formData = new FormData();
      formData.append("file", file);
      // 调用param中的钩子函数处理各种情况，这样就可以用在组件中用钩子了。也可以用res.code==200来进行判断处理各种情况
      imageUpload(formData, param)
        .then((res) => {
          if (res.data.code == 1) {
            this.form.imageone = res.data.data.path;
          }
        })
        .catch((err) => {
          param.onError(err);
        });
    },
    beforeAvatarUpload(file) {
      if (file.size > 500000)
        return this.$message.error("上传头像图片大小不能超过 5mb!");
    },
    addGoods() {
      this.title = "新增商品";
      this.dialogFormVisible = true;
      this.form={}
    },

    getList() {
      goodsListApi({
        page: this.page,
        pageSize: this.pageSize,
      }).then((res) => {
        console.log(res);
        if (res.data.code == 1) {
          this.tableData = res.data.data;
          this.total = res.data.total;
        }
        if (res.data.code == 401) {
          this.$message({
            type: "error",
            message: res.data.msg,
            duration: 1000,
            onClose: () => {
              router.replace("/login");
            },
          });
        }
      });
    },
    deleteGoods(id) {
      //这里加一层modle判断确认是否删除
      this.$confirm("确认要删除这件商品吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
            goodsDeleteApi({ id: id }).then((res) => {
            console.log(res);
            if (res.data.code == 1) {
              this.$message({
                type: "success",
                message: res.data.msg,
                duration: 1500,
                onClose: () => {
                  this.getList();
                },
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log("用户点击了取消");
        });
    },
    editGoods(id) {
      this.title = "修改商品信息";
      this.dialogFormVisible = true;
      goodsDetailApi(id).then((res) => {
        if (res.data.code == 1) {
          this.form = res.data.data;
        } else {
          this.$message({
            type: "error",
            message: "获取数据失败",
          });
        }
      });
    },
    onSubmit() {
      this.$refs.goodsForm.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            goodsEditApi(this.form).then((res) => {
              if (res.data.code == 1) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1500,
                  onClose: () => {
                    this.getList();
                    this.dialogFormVisible = false;
                  },
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            });
          } else {
            goodsAddApi(this.form).then((res) => {
              if (res.data.code == 1) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  duration: 1500,
                  onClose: () => {
                    this.getList();
                    this.dialogFormVisible = false;
                  },
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.msg,
                });
              }
            });
          }
        } else {
          this.$message({
            type: "warning",
            message: "请填写完整信息",
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.bigbox {
  display: flex;
  background-color: white;
  padding-top: 20px;
  margin-bottom: 20px;
  padding-left: 20px;
}

.tableData_image {
  width: 180px;
  height: 100px;
}
.bannerImage {
    width: 200px;
    height: 200px;
}

.el-pagination {
  margin-top: 20px;
}
</style>
